package argo.review;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Merge {

    public int[][] merge(int[][] intervals) {
        List<int[]> res = new ArrayList<>();

        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        int preMin = intervals[0][0];
        int preMax = intervals[0][1];
        for (int[] interval : intervals) {
            if (interval[0] <= preMax) {
                if (interval[1] > preMax) {
                    preMax = interval[1];
                }
            } else {
                res.add(new int[]{preMin, preMax});
                preMin = interval[0];
                preMax = interval[1];
            }
        }

        if ( preMax >= intervals[intervals.length - 1][1]) {
            res.add(new int[]{preMin, preMax});
        }

        return res.toArray(new int[res.size()][]);

    }
}
